package com.zhangdi.dwtools.security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AESUtils {
    private String ALGORITHM = "AES";
    private String MODE = "AES/ECB/PKCS5Padding";
    protected byte[] key_raw = {122, 104, 97, 110, 103, 100, 105, 64, 119, 119, 46, 49, 48, 48, 55, 33};

    public String Encrypt(String content) {
        byte[] encrypted;
        try {
            Cipher cipher = Cipher.getInstance(MODE);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key_raw, ALGORITHM));
            encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException |
                NoSuchPaddingException |
                InvalidKeyException |
                BadPaddingException |
                IllegalBlockSizeException e) {
            e.printStackTrace();

            return null;
        }

        return DatatypeConverter.printBase64Binary(encrypted);
    }

    public String Decrypt(String sSrc) {
        try {
            Cipher cipher = Cipher.getInstance(MODE);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key_raw, ALGORITHM));
            byte[] encrypted = DatatypeConverter.parseBase64Binary(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted);
                return new String(original, StandardCharsets.UTF_8);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        AESUtils aesUtils = new AESUtils();

        // 需要加密的字串
        String cSrc = "111";
        System.out.println(cSrc);
        // 加密
        String enString = aesUtils.Encrypt(cSrc);
        System.out.println("加密后的字串是：" + enString);

        // 解密
        String DeString = aesUtils.Decrypt(enString);
        System.out.println("解密后的字串是：" + DeString);
    }
}
